package com.abc.pro.util;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;



public class AsyncTaskManager {
    private static final int CORE_POOL_SIZE = 3;
    private static final int MAXIMUM_POOL_SIZE = 6;
    private static final int KEEP_ALIVE = 5;
    
    private static final BlockingQueue<Runnable> sWorkQueue =
            new LinkedBlockingQueue<Runnable>();
    
    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(0);
        
        public Thread newThread(Runnable r) {
            return new Thread(r, "AsyncTaskManager #" + mCount.getAndIncrement());
        }
    };
    
    private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
            MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
    
    public static ExecutorService getExecutors() {
        return sExecutor;
    }
    
    public static void wait(Runnable task) {
        if (task == null) return;
        try {
            sExecutor.execute(task);
        } catch (RejectedExecutionException e) {
            Logger.e("RejectedExecutionException", e.getMessage());
        }
    }
    
    public static Future<?> submit(Runnable task) {
        Future<?> future = null;
        try {
            future = sExecutor.submit(task);
        } catch (RejectedExecutionException e) {
            e.printStackTrace();
        }
        return future;
    }
    
    public static void destory() {
        sExecutor.shutdown();
        sExecutor.shutdownNow();
    }
}